<template>
  <div class="view">
    <div class="remind-breadcrumb flex">
      <div @click="handleToRemind" style="cursor: pointer;">{{ $t('candyBox.vipTool') }}</div>
      <div>></div>
      <div v-if="bindStatus === 0">{{ $t('ndxStake.setEmail') }}</div>
      <div v-else-if="bindStatus === 1">{{ $t('ndxStake.changeEmail') }}</div>
    </div>
    <div class="remind-content">
      <!-- 邮箱绑定/修改 -->
      <el-form class="bind" :class="{'hidden': bindSuccess}" :model="formBind" ref="formBind" :rules="rules">
        <el-form-item
          class="mb0"
          prop="emailAddress">
          <el-input
            :disabled="changeStep === 0 && this.bindStatus === 1"
            v-model="formBind.emailAddress"
            :placeholder="$t('ndxStake.enterNewEmail')"
            class="remind-input"></el-input>
        </el-form-item>
        <!-- 打开邮箱 -->
        <div class="openEmail clearfix" style="min-height: 1px">
          <span class="blueColor fr"
          @click="handleToOpenEmail"
          v-if="handleEmailHost() && formBind.emailAddress">{{ $t('ndxStake.openEmail') }}</span>
        </div>
        <!-- 图片验证码 -->
        <el-form-item class="imgCode clearfix" prop="imageCode" v-if="imgCodeShow">
          <el-input
            v-model="formBind.imageCode"
            :placeholder="$t('ndxStake.enterCode')"
            class="imgInput fl">
          </el-input>
          <img
            :src="`${targetOrigin}/api/account/getImageCaptcha?account=${$store.state.app.scatter.identity.accounts[0].name}&v=${vesen}`"
            class="fr"
            @click="handleGetImageCode" />
        </el-form-item>
        <!-- 输入验证码 -->
        <el-form-item class="mb0 codeInput" prop="emailCode" :class="{'remind-disable-btn': !sendEmailCode}">
          <el-input
            v-model="formBind.emailCode"
            :placeholder="$t('ndxStake.inputCode')"
            class="remind-input"
            @keyup.enter.native="handleSubmitBind">
              <!-- <template slot="append">
                <span  @click="handleGetCode" v-if="sendEmailCode">{{ $t('ndxStake.getCode') }}</span>
                <span v-else>{{ $t('ndxStake.reacquire') }}({{ countDownEmail }}s)</span>
              </template> -->
          </el-input>
          <div class="slot" @click="handleGetCode" v-if="sendEmailCode">{{ $t('ndxStake.getCode') }}</div>
          <div class="slot" v-else>{{ $t('ndxStake.reacquire') }}({{ countDownEmail }}s)</div>
        </el-form-item>
        <!-- 绑定 确认 -->
        <el-form-item class="mb0" style="margin-top: 15px;">
          <el-button
            type="primary"
            style="width: 324px; margin-top: 20px;"
            class="remind-btn"
            v-loading="bindLoading"
            :disabled="!bindDisabled"
            @click="handleSubmitBind">{{ $t('public.sure') }}</el-button>
        </el-form-item>
      </el-form>
      <!-- 绑定成功 -->
      <div class="bind" :class="{'hidden': !bindSuccess}">
        <i class="iconfont el-icon-circle-check"></i>
        <span class="color333 success" v-if="bindStatus === 1 && changeStep === 1">{{ $t('ndxStake.changeSuccess') }}</span>
        <span class="color333 success" v-else>{{ $t('ndxStake.bindSuccess') }}</span>
        <el-button
          type="primary"
          style="width: 324px; margin-top: 20px;"
          class="remind-btn"
          @click="handleToRemind">{{ $t('ndxStake.return') }}({{ countDownSuccess }}s)</el-button>
      </div>
    </div>
    <a :href="goEmailUrl" target="_blank" ref="goEmailUrl"></a>
  </div>
</template>

<script>
// import { EosModel } from '@/utils/eos';
import { EmailHost, validateEmail, authorized, getReqUrl } from '@/utils/validate';

export default {
  name: 'bindEmail', // 绑定邮箱 - 修改邮箱
  data() {
    return {
      user: {
        email: '',
      },
      countDownEmail: '', // 获取邮箱验证码倒计时
      sendEmailCode: true, // 发送邮箱验证
      formBind: {
        emailAddress: '', // 邮箱
        emailCode: '', // 邮箱验证码
        imageCode: '', // 图片验证码
      },
      rules: {
        emailAddress: [
          // { required: false, message: this.$t('lg.user2'), trigger: 'blur' },
          { type: 'email', message: this.$t('ndxStake.inputRightCode'), trigger: ['blur'] }
        ],
        imageCode: [
          { required: true, message: this.$t('ndxStake.enterCodeFirst'), trigger: ['blur'] }
        ]
      },
      goEmailUrl: null, // 邮箱跳转地址
      timer: null, // 计时器
      bindLoading: false,
      bindSuccess: false,
      bindStatus: 0, // 0-绑定，1-修改
      changeStep: 0, // 修改步骤0验证， 1绑定
      countDownSuccess: 5, // 绑定或修改成功倒计时数
      timerSuccess: null, // 绑定或修改成功倒计时
      imgCodeShow: false, // 是否显示图形验证码
      targetOrigin: '', // 图片验证码网站前缀
      vesen: '', // 随机码
    }
  },
  props: {
    // bindStatus: {
    //   type: Number,
    //   default: 0
    // }
  },
  computed: {
    bindDisabled() {
      return this.formBind.emailAddress !== '' && this.formBind.emailCode !== '';
    },
  },
  watch: {
    '$store.state.app.language': function change() {
      this.rules = {
        emailAddress: [
          { type: 'email', message: this.$t('ndxStake.inputRightCode'), trigger: ['blur'] }
        ],
        imageCode: [
          { required: true, message: this.$t('ndxStake.enterCodeFirst'), trigger: ['blur'] }
        ]
      };
    }
  },
  created() {
  },
  mounted() {
    this.user = this.$store.state.app.accountInfo;
    this.formBind.emailAddress = this.user ? this.user.email || '' : '';
    this.goEmailUrl = this.handleEmailHost();
    this.bindStatus = this.user.email ? 1 : 0;
    const env = process.env.NODE_ENV;
    switch (env) {
      case 'development':
        this.targetOrigin = getReqUrl();
        break;
      default:
        this.targetOrigin = window.location.origin;
        break;
    }
    this.vesen = new Date().getTime();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.timerSuccess) {
      clearInterval(this.timerSuccess);
    }
  },
  methods: {
    // 回到会员服务首页
    handleToRemind() {
      this.$router.push({ name: 'services' });
    },
    // 获取验证码 之 授权判断
    handleGetCode() {
      if (this.imgCodeShow && !this.formBind.imageCode) {
        this.$refs.formBind.validateField('imageCode');
        return;
      }
      const token = localStorage.getItem('Frontend-Token');
      if (token) {
        this.handleGetCodeAction();
        return;
      }
      // 获取授权
      this.handleAuthorized(() => {
        this.handleGetCodeAction();
      });
    },

    // 获取验证码
    handleGetCodeAction() {
      const email = this.formBind.emailAddress;
      this.$refs.formBind.validateField('emailAddress');
      if (!validateEmail(email)) return;
      // 判断新旧邮箱有没相同
      const userEmail = this.$store.state.app.accountInfo.email;
      if (this.changeStep === 1 && email === userEmail) {
        this.$message.error(this.$t('ndxStake.newOldDiff'));
        return;
      }
      this.countDownEmail = 60;
      this.sendEmailCode = false;
      const params = {
        email,
        imageCode: this.formBind.imageCode,
      };
      this.$http.post('/account/sendMailVerifyCode', params).then((res) => {
        if (res.code === 1011) {
          this.$message.error(this.$t('ndxStake.codeError'));
          this.formBind.imageCode = '';
          this.handleGetImageCode();
          this.sendEmailCode = true;
          return;
        }
        if (res.code === 1025) {
          this.$message.error(this.$t('ndxStake.enterCorrectCode'));
          this.formBind.imageCode = '';
          this.handleGetImageCode();
          this.sendEmailCode = true;
          return;
        }
        if (res.code === 1026) {
          this.$message.error(this.$t('ndxStake.enterCorrectCode'));
          this.sendEmailCode = true;
          return;
        }
        if (res.code !== 0) {
          // this.$message.error(this.$t('ndxStake.codeErrorAgain'));
          this.imgCodeShow = res.todayCount > 5 ? 1 : 0;
          // this.handleGetImageCode();
          this.sendEmailCode = true;
          return;
        }
        this.$message.success(this.$t('ndxStake.codeSuccess'));
        // 进入倒计时
        this.timer = setInterval(() => {
          if (!this.countDownEmail) {
            clearInterval(this.timer);
            this.countDownEmail = 60;
            this.sendEmailCode = true;
            return;
          }
          this.countDownEmail -= 1;
        }, 1000);
      });
    },
    // 获取图片验证码
    handleGetImageCode() {
      this.vesen = new Date().getTime();
    },
    // 邮箱绑定
    handleSubmitBind() {
      if (!this.formBind.emailCode) {
        return;
      }
      const token = localStorage.getItem('Frontend-Token');
      if (!token) {
        this.$message.error(this.$t('ndxStake.getVeriCode'));
        return;
      }
      this.bindLoading = true;
      if (this.bindStatus === 1 && this.changeStep === 0) {
        // 去验证
        this.handleVerifyOriginEmail();
        return;
      }
      const params = {
        verifyCode: this.formBind.emailCode,
        email: this.formBind.emailAddress,
        imageCode: this.formBind.imageCode,
      }
      this.$http.post('/account/bindOrModEmail', params).then((res) => {
        this.bindLoading = false;
        if (res.code !== 0) {
          switch (res.code) {
            case 1010:
              this.$message.error(this.$t('ndxStake.emailFormatError'));
              break;
            case 1011:
              this.$message.error(this.$t('ndxStake.codeError'));
              break;
            case 1012:
              this.$message.error(this.$t('ndxStake.newOldDiff'));
              break;
            default:
              this.$message.error(res.msg);
              break;
          }
          return;
        }
        this.bindSuccess = true;
        if (this.bindSuccess) {
          this.timerSuccess = setInterval(() => {
            if (this.countDownSuccess <= 1) {
              clearInterval(this.timerSuccess);
              this.countDownSuccess = 5;
              this.$router.push({ name: 'services' });
            }
            this.countDownSuccess -= 1;
          }, 1000);
        }
        this.user.email = this.formBind.emailAddress;
        // 更新vuex accountInfo 值
        this.$store.dispatch('setAccountInfo', this.user);
      })
    },

    // 验证旧邮箱
    handleVerifyOriginEmail() {
      const params = {
        verifyCode: this.formBind.emailCode,
        email: this.formBind.emailAddress,
        imageCode: this.formBind.imageCode,
      }
      this.$http.post('/account/verifyOriginEmail', params).then((res) => {
        this.bindLoading = false;
        if (res.code !== 0) {
          switch (res.code) {
            case 1010:
              this.$message.error(this.$t('ndxStake.emailFormatError'));
              break;
            case 1011:
              this.$message.error(this.$t('ndxStake.codeError'));
              break;
            case 1012:
              this.$message.error(this.$t('ndxStake.newOldDiff'));
              break;
            case 1023:
              this.$message.error(this.$t('ndxStake.enterCorrectCode'));
              break;
            default:
              this.$message.error(res.msg);
              break;
          }
          return;
        }
        this.countDownEmail = 60;
        this.sendEmailCode = true;
        this.formBind.imageCode = '';
        this.imgCodeShow = 0;
        this.handleGetImageCode();
        clearInterval(this.timer);
        this.formBind.emailAddress = '';
        this.formBind.emailCode = '';
        this.changeStep = 1; // 验证成功
      });
    },
    // 获取邮箱跳转地址
    handleEmailHost() {
      const email = this.formBind.emailAddress;
      return EmailHost(email);
    },
    // 跳转邮箱
    handleToOpenEmail() {
      this.goEmailUrl = this.handleEmailHost();
      setTimeout(() => {
        this.$refs.goEmailUrl.click();
      }, 50);
    },

    // 授权操作
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          return;
        }
        callback();
      });
    },
  },
}
</script>

<style scoped lang="scss">
@import '@/views/myWallet/user.scss';
@import '@/assets/css/variables.scss';
@import '@/views/myWallet/eosResource/resource.scss';

$-color: #278EDA;
.blueColor {
  color: $-color !important;
}

.color333 {
  color: #333 !important;
}

.view {
  padding-bottom: 100px;

  .remind-breadcrumb {
    padding: 30px 0 0 40px;
    margin-bottom: 70px;
    color: #333;

    div:nth-child(2) {
      margin: 0 10px;
    }
  }

  .remind-content {
    width: 324px;
    margin: 0 auto;

    .codeInput {
      position: relative;
      .slot {
        position: absolute;
        right: 0;
        top: 0;
        min-width: 100px;
        text-align: center;
        cursor: pointer;
        color: #278EDA;
      }
    }

    .bind {
      // padding: 55px 118px;
      color: #999;
      margin-bottom: 5px;

      .success {
        margin: 20px 0 25px 0;
      }

      .verification {
        margin: 30px 0;
      }

      .remind-disable-btn {
        .slot {
          color: #999;
        }
      }

      i {
        display: block;
        font-size: 80px;
        color: #259B24;
        text-align: center;
      }

      span {
        display: block;
        text-align: center;
      }
    }

    .openEmail {
      width: 324px;
      margin: 10px 0;
      height: 20px;

      .blueColor {
        cursor: pointer;
      }
    }

    .imgCode {
      margin-bottom: 20px;

      .imgInput {
        width: 60%;
      }

      img {
        display: inline-block;
        width: 35%;
        height: 40px;
        border: 1px solid #000;
      }
    }
  }
}

/deep/ .el-input-group__append {
  width: 120px;
}

/deep/ .el-form-item.is-success .el-input__inner {
  border-color: #dcdfe6;
}

.theme-1B1D27{
  .remind-input {
    /deep/ .el-input-group__append {
      border-color: #4e5b85;
    }
  }
  .success {
    color: rgba(255, 255, 255, 0.8) !important;
  }
  .remind-breadcrumb {
    color: rgba(255, 255, 255, 0.6);
  }
}

</style>
